<?php

/**

 * Created by PhpStorm.

 * User: win7

 * Date: 2018/5/21 0021

 * Time: 10:06

 */



namespace Wx\Controller;

use Think\Controller;

use Wx\Model\ForetasteModel;

use Wx\Model\shareModel;

use Wx\Model\SendMsgModel;

class ForetasteController extends CommonController

{

    public function _initialize(){

        parent::_initialize();

        $goods = M("foretaste_goods")->where("state = 1")->select();//所有商品

        foreach($goods as $gk => $gv){
            //活动商品--库存为0结束
            if ($gv['num'] > 0){
                // 活动商品——活动时间内
                if (time() <= $gv['endtime']) {

                    //获取该商品活动的商品订单--完成集赞的
                    $order = M("foretaste_order")->where("g_id = {$gv['id']}  AND population >= {$gv['praise_num']} AND state = 0")->select();

                    //订单处理
                    foreach ($order as $ok => $ov){
                        //申请中的订单
                        $usetime = time()-$ov['addtime'];//参与时间
                        M("foretaste_order")->where("id = {$ov['id']}")->save(['endtime'=>time(),'state'=>1,'usetime'=>$usetime]);//完成点赞，自动成功
                        M('foretaste_goods')->where("id = {$ov['g_id']}")->setDec('num',1);//减库存
//                        $member = M('member')->where("id = {$ov['u_id']}")->find();
//                        $credit = $member['credit1']+floatval($ov['price']);
//                        $save_credit = M('member')->where("id = {$ov['u_id']}")->save(['credit1'=>$credit]);
//                        if ($save_credit){
                        //积分记录
//                            $credit_log = array(
//                                'u_id' => $member['id'],
//                                'credit_type' => 'credit1',
//                                'change_number' => $ov['price'],
//                                'change_type' => '+',
//                                'reason' => '试吃活动失败返还',
//                                'changetime' => time()
//                            );
//                            M("member_credit_log")->add($credit_log);//积分记录
//                            M("voice")->add(['u_id'=>$ov['u_id'],'content'=>'因未能完成集赞，您参与的试吃活动失败,积分已退回到您的账户!','sendtime'=>time()]);
//                            D("SendMsg")->senderror($ov['u_id'],'试吃','试吃申请',"申请失败","因未能完成集赞，您参与的试吃活动失败!","点击查看详情>>>>>","http://www.xiangtws.com/index.php/Wx/ForetasteOrder/order/oid/".$ov['id']);
                        M("voice")->add(['u_id'=>$ov['u_id'],'content'=>'您成功参与了试吃活动，请等待发货通知!','sendtime'=>time()]);
                        D("SendMsg")->sendsuccess($ov['u_id'],'试吃','试吃申请',date("Y-m-d H:i:s",$ov['addtime']),"点击查看详情>>>>>","http://www.xiangtws.com/index.php/Wx/ForetasteOrder/order/oid/".$ov['id']);
//                        }//end if

//                        //待成功的订单
//                        if($ov['state'] == 7){
//                            $order_success = M("foretaste_order")->where("g_id = {$gv['id']} AND state = 7")->order('usetime')->select();//订单排名
//
//                            foreach ($order_success as $sk => $sv){
//                                if($sk < 3){
//                                    M("foretaste_order")->where("id = {$sv['id']}")->save(['state'=>1]);//完成申请
//                                    M("voice")->add(['u_id'=>$sv['u_id'],'content'=>'您成功参与了试吃活动，请等待发货通知!','sendtime'=>time()]);
//                                    D("SendMsg")->sendsuccess($sv['u_id'],'试吃','试吃申请',date("Y-m-d H:i:s",$sv['addtime']),"点击查看详情>>>>>","http://www.xiangtws.com/index.php/Wx/ForetasteOrder/order/oid/".$sv['id']);
//                                }else{
//                                    M("foretaste_order")->where("id = {$sv['id']}")->save(['state'=>6]);//申请失败
//                                    $member = M('member')->where("id = {$sv['u_id']}")->find();
//                                    $credit = $member['credit1']+floatval($sv['price']);
//                                    $save_credit = M('member')->where("id = {$sv['u_id']}")->save(['credit1'=>$credit]);
//                                    if ($save_credit){
//                                        //积分记录
//                                        $credit_log = array(
//                                            'u_id' => $member['id'],
//                                            'credit_type' => 'credit1',
//                                            'change_number' => $sv['price'],
//                                            'change_type' => '+',
//                                            'reason' => '试吃活动失败返还',
//                                            'changetime' => time()
//                                        );
//                                        M("member_credit_log")->add($credit_log);//积分记录
//                                        M("voice")->add(['u_id'=>$sv['u_id'],'content'=>'未能成为前三名，您参与的试吃活动失败,积分已退回到您的账户!','sendtime'=>time()]);
//                                        D("SendMsg")->senderror($sv['u_id'],'试吃','试吃申请',"申请失败","未能成为前三名，您参与的试吃活动失败!","点击查看详情>>>>>","http://www.xiangtws.com/index.php/Wx/ForetasteOrder/order/oid/".$sv['id']);
////                                    M("voice")->add(['u_id'=>$sv['u_id'],'content'=>'试吃活动失败，退回'.$sv['price'].'积分','sendtime'=>time()]);
//                                    }//end if
//                                }//end if
//                            }//end foreach
//                        }//end if

                    }//end foreach
//                    M("foretaste_goods")->where("id = {$gv['id']}")->save(['state' => 4]);//结束活动
                }else{
                    //获取该商品活动的商品订单--未完成集赞的
                    $order = M("foretaste_order")->where("g_id = {$gv['id']} AND state = 0")->select();
                    //订单处理
                    foreach ($order as $ok => $ov){
                        //申请中的订单
                        M("foretaste_order")->where("id = {$ov['id']}")->save(['state'=>6]);//完成点赞，自动失败
                        $save_credit = M('member')->where("id = {$ov['u_id']}")->setInc('credit1',floatval($ov['price']));//退积分
                        if ($save_credit){
                            //积分记录
                            $credit_log = array(
                                'u_id' => $ov['u_id'],
                                'credit_type' => 'credit1',
                                'change_number' => $ov['price'],
                                'change_type' => '+',
                                'reason' => '试吃活动失败返还',
                                'changetime' => time()
                            );
                            M("member_credit_log")->add($credit_log);//积分记录
                            M("voice")->add(['u_id'=>$ov['u_id'],'content'=>'您参与的试吃活动失败,积分已退回到您的账户!','sendtime'=>time()]);
                            D("SendMsg")->senderror($ov['u_id'],'试吃','试吃申请',"申请失败","您参与的试吃活动失败!","点击查看详情>>>>>","http://www.xiangtws.com/index.php/Wx/ForetasteOrder/order/oid/".$ov['id']);
                            M("voice")->add(['u_id'=>$ov['u_id'],'content'=>'试吃活动失败，退回'.$ov['price'].'积分','sendtime'=>time()]);
                        }//end if
                    }//end foreach $order
                    M("foretaste_goods")->where("id = {$gv['id']}")->save(['state' => 4]);//结束活动
                }//end if $gv.endtime
            }else{
                //获取该商品活动的商品订单--未完成集赞的
                $order = M("foretaste_order")->where("g_id = {$gv['id']} AND state = 0")->select();
                //订单处理
                foreach ($order as $ok => $ov){
                    //申请中的订单
                    M("foretaste_order")->where("id = {$ov['id']}")->save(['state'=>6]);//完成点赞，自动失败
                    $save_credit = M('member')->where("id = {$ov['u_id']}")->setInc('credit1',floatval($ov['price']));//退积分
                    if ($save_credit){
                        //积分记录
                        $credit_log = array(
                            'u_id' => $ov['u_id'],
                            'credit_type' => 'credit1',
                            'change_number' => $ov['price'],
                            'change_type' => '+',
                            'reason' => '试吃活动失败返还',
                            'changetime' => time()
                        );
                        M("member_credit_log")->add($credit_log);//积分记录
                        M("voice")->add(['u_id'=>$ov['u_id'],'content'=>'您参与的试吃活动失败,积分已退回到您的账户!','sendtime'=>time()]);
                        D("SendMsg")->senderror($ov['u_id'],'试吃','试吃申请',"申请失败","您参与的试吃活动失败!","点击查看详情>>>>>","http://www.xiangtws.com/index.php/Wx/ForetasteOrder/order/oid/".$ov['id']);
                        M("voice")->add(['u_id'=>$ov['u_id'],'content'=>'试吃活动失败，退回'.$ov['price'].'积分','sendtime'=>time()]);
                    }//end if
                }//end foreach $order
                M("foretaste_goods")->where("id = {$gv['id']}")->save(['state' => 4]);//结束活动
            }//end if $gv.num
        }//end foreach $goods

        //扶贫大使活动时间-start
        $helppoor = M("helppoor")->select();
        if (isset($helppoor)){
            foreach ($helppoor as $hk => $hv){
                if (time() >= $hv['starttime'] && $hv['state'] == 0){
                    M("helppoor")->where("id = {$hv['id']}")->save(['state'=>1]);//开始排名
                }//end if
                if (time() > $hv['endtime'] && $hv['state'] == 1){
                    M("helppoor")->where("id = {$hv['id']}")->save(['state'=>2]);//结束排名
                    $ranking_info = M("foretaste_ranking")->where("h_id = {$hv['id']}")->order('eva_num desc')->select();//查看排名
                    $member_id = array();
                    foreach ($ranking_info as $k => $v){
                        if (!array_key_exists($v['c_id'],$member_id)){
                            $member_id[$v['c_id']]=$v['u_id'];//获取小区第一
                            M("voice")->add(['u_id'=>$v['u_id'],'content'=>'恭喜您成为扶贫大使，获得恩施三天游的机会!','sendtime'=>time()]);//通知
                            D("SendMsg")->sendsuccess($v['u_id'],'扶贫排行','扶贫大使排行，恩施3日游',date("Y-m-d H:i:s",time()),"点击查看详情>>>>>","http://www.xiangtws.com/index.php/Wx/Foretaste/helppoor");
                        }//end if
                    }//end foreach
                    $member_id=implode(',',array_slice($member_id,0,$hv['success_num']));//转换为字符串
                    //处理多余的逗号
                    $member_id=preg_replace('/(,)+/i',',',$member_id);
                    $member_id=rtrim($member_id,',');//去尾
                    $member_id=ltrim($member_id,',');//去头
                    M("helppoor")->where("id = {$hv['id']}")->save(['member_ranking'=>$member_id]);//成功用户排名
                }//end if
            }//end foreach
        }//end if
        //扶贫大使活动时间-end

        //未关注的存储到xcache中，程序轮询检测（关注后推送最近浏览的商品信息）-start
        if(session('focus')==0 && session('u_id')>0){
            $focusmsg=new \Wx\Controller\AutofocusmsgController();  //用绝对路径找
            $focusmsg->setxcache(session('u_id'),"参与试吃活动",'http://www.xiangtws.com'.$_SERVER['REQUEST_URI']);
        }//end if
        //未关注的存储到xcache中，程序轮询检测（关注后推送最近浏览的商品信息）-end
    }//end fun


    //活动主页

    public function index(){
        $cate = isset($_POST['cate']) ? $_POST['cate'] : 'start';//默认类型

        if($cate == 4){
            $where = "state = ".$cate;//结束
        }else{
            if ($cate == 'start'){
                $where = "state = 1 AND starttime <= ".time();//开始
            }else{
                $where = "state = 1 AND starttime > ".time();//未开始
            }//end if
        }//end if
        $foretaste = M("foretaste_goods")->where($where)->order('starttime ASC,addtime DESC')->select();//获取商品信息
        foreach ($foretaste as $k =>$v){
            //商品状态
            switch ($cate){
                case 'start':
                    $foretaste[$k]['button'] = "申请".getunit($v['category']);//通过
                    break;
                case 'nostart':
                    $foretaste[$k]['button'] = '即将'.getunit($v['category']);//待审核
                    break;
                case 4:
                    $foretaste[$k]['button'] = "查看".getunit($v['category']);//已结束
                    break;
            }//end switch
        }//end foreach

        $this->assign('cate',$cate);
        $this->assign("foretaste",$foretaste);
        $this->display("foretaste");

    }//end fun index()


    //商品详情

    public function pro(){

        $id = $_GET['gid'];//商品id

        $op = $_POST['op'] ? $_POST['op']:'display';

        $u_id = session("u_id");//用户id

        $foretaste = M("foretaste_goods")->where("id = {$id}")->find();//商品信息

        /*------------------------------------用户信息检测-start----------------------------------------*/
        if ($op == 'receive'){
            //检测用户必填信息
            $member = M("member")->where("id = {$u_id}")->field('c_id,mobile,realname,hometown')->find();
            //用户信息是否完备
            if (in_array('',$member)){
                $this->ajaxReturn(['val'=>'member'],'JSON');
            }//end if

            //判断是否为武汉地区
            $community_id = M("shop_community")->where("id = {$member['c_id']}")->getField('a_id_2');
            if ($community_id != 408534){
                $this->ajaxReturn(['val'=>'community'],'JSON');
            }//end if

            //用户拥有积分
            $member_price = getMember($u_id,"credit1");
            //用户积分是否充足
            if (intval($member_price['credit1']) < $foretaste['price']){
                $this->ajaxReturn(['val'=>'credit'],'JSON');
            }//end if

            //获取当天凌晨0点时间戳
            $timestr = strtotime(date('Y-m-d',time()));

            //获取当天在这一周的第几天
            $now_day = date('w',$timestr)-1;

            //获取周一
            $monday_str = $timestr - $now_day*60*60*24;

            //获取周日
            $sunday_str = $timestr + (6-$now_day)*60*60*24;

            //获取一周内的交易次数
            $num_order = M("foretaste_order")->where("u_id = {$u_id} AND addtime >= {$monday_str} AND addtime <= {$sunday_str} AND state != 6")->field("state,count(id) as num")->find();
            //用户是否有购买资格
            if ($num_order['num'] > 0){
                $this->ajaxReturn(['val'=>'order','state'=>$num_order['state']],'JSON');
            }//end if
        }//end if

        /*------------------------------------用户信息检测-end------------------------------------------*/

        if ($op == 'display'){
            //获取当前网页，个人信息在补充完成后跳转到该详情页面
            $path =  $_SERVER['REQUEST_URI'];
            session("pro_url",$path);

            /*--------------------------------- 申请列表-start----------------------------------------------*/
            $goods = M("foretaste_goods")->where("id = {$id}")->find();//获取商品信息

            //         获取订单信息
            $order = M("foretaste_order")
                ->where("g_id = {$id} AND state in (0,1,2,3,4,5)")
                ->order("population DESC,usetime,u_id")
                ->select();

            //获取订单用户信息处理
            foreach ($order as $k => $v){

                $order[$k]['nickname'] = M('member')->where("id = {$v['u_id']}")->getField("nickname");//获取用户昵称

                $order[$k]['avatar'] = M('member')->where("id = {$v['u_id']}")->getField("avatar");//获取用户头像

                $order[$k]['pre'] = ($v['population']/8)*100;//获取百分比值

                $order[$k]['pre'] = $order[$k]['pre'] > 100? 100 :$order[$k]['pre'] ;//获取百分比值

                /*--------------完成所用时间处理-start--------------*/
                $hour = intval($v['usetime']/60/60);//小时

                $v['usetime'] = $v['usetime']-$hour*60*60;//去除小时后剩余时间
                $minute = intval($v['usetime']/60);//分钟

                $second = $v['usetime']-$minute*60;//秒

                $order[$k]['str_time'] = '';
                //      字符串拼接时间
                //      小时
                if ($hour != 0){
                    $hour=str_pad($hour,2,"0",STR_PAD_LEFT);//自动补零
                    $order[$k]['str_time'] .= $hour.'时';
                }//end if

                //      分钟
                if ($minute != 0){
                    $minute=str_pad($minute,2,"0",STR_PAD_LEFT);//自动补零
                    $order[$k]['str_time'] .= $minute.'分';
                }//end if

                //      秒
                $order[$k]['str_time'] .= $second.'秒';
                /*--------------完成所用时间处理-end--------------*/

            }
            /*------------------------------------- 申请列表-end -------------------------------------------------------*/


            /*------------------------------------- 评论-start -------------------------------------------------------*/
            $count = M('foretaste_evaluate')->where('g_id = '.$id)->count();//评价总数

            //      评价详情
            $list = M('foretaste_evaluate')
                ->table(C('DB_PREFIX')."foretaste_evaluate as e")
                ->join(C('DB_PREFIX')."member as m ON m.id=e.u_id")
                ->field('e.*,m.nickname,m.avatar,m.hometown')
                ->where("e.g_id=".$id." AND state = 1")
                ->order('id desc')
                ->limit(3)
                ->select();

            //评论数据处理
            foreach ($list as $k => $v){

                //用户匿名处理
                if ($v['is_inco'] == 0){
                    $list[$k]['nickname']='匿名';
                }

                $list[$k]['comm_num'] = M('evaluate_comment')->where('e_id = '.$v['id'])->count();  //评论数
                $list[$k]['pic'] = $var=explode(",",$v['pic']);              //处理评价图片
            }
            /*------------------------------------- 评论-end -------------------------------------------------------*/
            //倒计时
            if ($foretaste['starttime'] > time()){
                $totime = $foretaste['starttime']-time();
            }else if($foretaste['starttime'] <= time() && time() <= $foretaste['endtime']){
                $totime =$foretaste['endtime']-time();
            }//end if

            //微信分享-start
            $wxshare=new shareModel(C('WX_API.appid'),C('WX_API.secret'));
            $signPackage=$wxshare->getSignPackage();
            /*
            *
            array(6) {
              ["appId"] => string(18) "wx6a0daaedc4d00100"
              ["nonceStr"] => string(16) "5cKMHQADQTbRkv2f"
              ["timestamp"] => int(1527576256)
              ["url"] => string(59) "http://www.xiangtws.com/index.php/Wx/Prodetail/index/id/20/"
              ["signature"] => string(40) "a70ef78304bc4f5558439b65955119806e4fb3fe"
              ["rawString"] => string(205) "jsapi_ticket=HoagFKDcsGMVCIY2vOjf9raVdUJqZ1stwmkyXwhMyovuJhCTHjtpRnNxRJSVQ0UacAdrqz97vWdzjRU3Dp-YYw&noncestr=5cKMHQADQTbRkv2f*tamp=1527576256&url=http://www.xiangtws.com/index.php/Wx/Prodetail/index/id/20/"
            }
            *
            */
            $this->assign('signPackage',$signPackage);//微信数据
            //微信分享-end

            $this->assign('count',$count);
            $this->assign('focus',session('focus'));
            $this->assign('list',$list);

            $this->assign("order",$order);

            $this->assign("goods",$goods);


            $this->assign($foretaste);
            $this->assign('totime',$totime);

            $this->assign("order_log",$order);

            $this->display("prodetail-sc");
        }//end if

    }//end fun pro()



    //商品检测

    public function reload(){

        $id = $_POST['id'];

        $foretaste = M("foretaste_goods")->where("id = {$id}")->field('state,num')->find();//商品信息

        $this->ajaxReturn($foretaste,"JSON");

    }



    //下单页面

    public function order(){

        $id = $_GET['gid'];

        $u_id = session("u_id");

        //获取用户信息和该社区店铺名

        $member = M("member")->alias("m")

            ->join("xtws_shop_store s ON m.c_id = s.c_id","LEFT")

            ->where("m.id = {$u_id}")

            ->field('m.*,s.storename')

            ->find();



        $foretaste = M("foretaste_goods")->where("id = {$id}")->find();//商品信息

        $this->assign($foretaste);

        $this->assign('member',$member);

        $this->display("confirmOrder-sc");

    }//end fun order()



    //支付

    public function pay(){

        $id = $_GET['gid'];

        $u_id = session("u_id");

        $member = M("member")->where("id = {$u_id}")->find();//检测用户信息

        $foretaste = M("foretaste_goods")->where("id = {$id}")->find();//商品信息

        /*--------------------------------用户购买权限-start--------------------------------*/
        //获取当天凌晨0点时间戳

        $timestr = strtotime(date('Y-m-d',time()));

        $now_day = date('w',$timestr)-1;

        //获取周一

        $monday_str = $timestr - $now_day*60*60*24;

        //获取周日

        $sunday_str = $timestr + (6-$now_day)*60*60*24;

        $num_order = M("foretaste_order")->where("u_id = {$u_id} AND g_id = {$foretaste['id']} AND addtime >= {$monday_str} AND addtime <= {$sunday_str} AND state != 6")->getField("count(id) as num");//获取一周内的交易次数

        if ($num_order > 0) {

            $this->error('违法操作');

        }else{

            $credit = $member['credit1']-floatval($foretaste['price']);

            if ($credit<0){
                $this->error("数据错误！");
            }
            /*--------------------------------用户购买权限-end--------------------------------*/

            /*-------------------------------支付和订单生成-start--------------------------------*/
            //生成取货码

            $order_sn = '';

            for ($i=0;$i<6;$i++){

                $order_sn .= rand(0,9);

            }

            $order = array(

                'u_id' => $u_id,

                'g_id' => $foretaste['id'],//商品id

                'order_sn' => $order_sn,

                'price' => $foretaste['price'],//支付金额

                'u_num' => $foretaste['u_num'],//商品规格

                'unit' => $foretaste['unit'],//规格单位

                'state' => 0,//0-申请中1-申请成功2-已发货3-待核销4-待评价5-已评价6-失败

                'addtime' => time()

            );

            $addorder = M("foretaste_order")->add($order);

            if ($addorder){

                $qrcode = D("Foretaste")->qrcode($addorder.'+'.$order_sn);//生成二维码

                M("foretaste_order")->where("id = {$addorder}")->save(['qrcode' => $qrcode]);//添加二维码的名字

                $member_save = M("member")->where("id = {$u_id}")->save(['credit1'=>$credit]);//扣除积分
                //积分记录
                $credit_log = array(
                    'u_id' => $u_id,
                    'credit_type' => 'credit1',
                    'change_number' => $foretaste['price'],
                    'change_type' => '-',
                    'reason' => '参与试吃活动',
                    'changetime' => time()
                );
                M("member_credit_log")->add($credit_log);//积分记录
                M("voice")->add(['u_id'=>$u_id,'content'=>'参与试吃活动，扣除'.$foretaste['price'].'积分','sendtime'=>time()]);//消息通知
                if($member_save){

                    $this->redirect('Foretaste/foretaster',['oid'=>$addorder]);

                }else{

                    M("foretaste_order")->where("id = {$member_save}")->delete();

                    $this->error("支付失败");

                }

            }else{

                $this->error("支付失败");

            }

        }
        /*-------------------------------支付和订单生成-end--------------------------------*/

    }//end fun pay()



    //成功页面后

    public function foretaster(){

        $id = $_GET['oid'];

        $op = $_POST['op'];

        $u_id = session("u_id");
        $focus = session('focus');

        $order = M("foretaste_order")->where("id = {$id}")->find();//订单信息

        $member =  M("member")->where("id = {$order['u_id']}")->find();//检测用户信息

        $myorder= M("foretaste_order")->where("u_id = {$u_id}")->field('id')->select();//当前用户的订单信息


        /*----------------------------判断是否为当前用户-start--------------------------------*/
        foreach($myorder as $k =>$v){

            $myorder[$k] = $v['id'];//获取当前用户的所有订单id

        }


        //判断当前用户是否为当前订单拥有者
        if(in_array($id,$myorder)){

            $member['is_me'] = "true";//是当前用户

        }else{

            $member['is_me'] = "false";//不是当前用户

            $mylog= M("foretaste_order_log")->where("u_id = {$u_id} AND o_id = {$id}")->getField('count(id) as num');//当前用户的点赞信息

            //是否已点赞
            if($mylog > 0){

                $member['is_praise'] = "true";

            }else{

                $member['is_praise'] = "false";

            }

        }//end if
        /*----------------------------判断是否为当前用户-end--------------------------------*/

        /*-----------------------------点赞-start---------------------------*/
        if($op == "praise"){

            $praise_arr = array(

                'u_id' => $u_id,

                'o_id' => $id,

                'addtime' => time()

            );

            $mylog= M("foretaste_order_log")->where("u_id = {$u_id} AND o_id = {$id}")->getField('count(id) as num');//当前用户的点赞信息

            if($mylog == 0){

                $praise = M("foretaste_order_log")->add($praise_arr);//添加点赞记录

                $population = $order['population']+1;

                if($praise){

                    $save_population = M("foretaste_order")->where("id = {$id}")->save(['population'=>$population]);//更新点赞人数

                    if ($save_population){

                        $this->ajaxReturn(array('state'=>0,'val'=>'点赞成功'),"JSON");

                    }else{

                        M("foretaste_order_log")->where("id = {$praise}")->delete();//删除点赞记录

                        $this->ajaxReturn(array('state'=>1,'val'=>'点赞失败'),"JSON");

                    }//end if

                }else{

                    $this->ajaxReturn(array('state'=>1,'val'=>'点赞失败'),"JSON");

                }//end if

            }else{

                $this->ajaxReturn(array('state'=>1,'val'=>'请勿重复点赞'),"JSON");

            }//end if

        }//end if

        $goods = M("foretaste_goods")->where("id = {$order['g_id']}")->find();//商品信息

        //获取点赞的用户信息

        $log = M("foretaste_order_log")->where("o_id = {$id}")->select();

        foreach ($log as $k => $v){
            $log_member[$k] = getMember($v['u_id'],'nickname,avatar');
            $log_member[$k]['nickname'] =mb_substr($log_member[$k]['nickname'],0,8,'utf-8');//截断过长的用户昵称
            $log_member[$k]['addtime'] = $v['addtime'];
        }
        /*-----------------------------点赞-end---------------------------*/

        $member['storename'] = M("shop_store")->where("c_id = {$member['c_id']}")->getField('storename');//获取店铺名称

        /*--------------完成所用时间处理-start--------------*/

        $hour = intval($order['usetime']/60/60);//小时

        $usetime = $order['usetime']-$hour*60*60;//去除小时后剩余时间
        $minute = intval($usetime/60);//分钟

        $second = $usetime-$minute*60;//秒

        $order[$k]['str_time'] = '';
        //      字符串拼接时间
        //      小时
        if ($hour != 0){
            $hour=str_pad($hour,2,"0",STR_PAD_LEFT);//自动补零
            $order['str_time'] .= $hour.'小时';
        }//end if

        //      分钟
        if ($minute != 0){
            $minute=str_pad($minute,2,"0",STR_PAD_LEFT);//自动补零
            $order['str_time'] .= $minute.'分钟';
        }//end if

        //      秒
        $order['str_time'] .= $second.'秒';
        /*--------------完成所用时间处理-end--------------*/

        //处理头部图像
        $goods['h_imgs'] = isMorePic($goods['h_imgs']);

        //总成功订单
        $goods['sumorder'] = M("foretaste_order")->where("g_id = {$goods['id']} AND addtime >= {$goods['starttime']} AND addtime <= {$goods['endtime']} AND state in (1,2,3,4,5)")->getField('count(id)');//订单信息

        $this->assign($goods);

        $this->assign('focus',$focus);
        $this->assign('order',$order);

        $this->assign('member',$member);

        $this->assign('log',$log_member);

        //微信分享-start
        $wxshare=new shareModel(C('WX_API.appid'),C('WX_API.secret'));
        $signPackage=$wxshare->getSignPackage();
        /*
        *
        array(6) {
          ["appId"] => string(18) "wx6a0daaedc4d00100"
          ["nonceStr"] => string(16) "5cKMHQADQTbRkv2f"
          ["timestamp"] => int(1527576256)
          ["url"] => string(59) "http://www.xiangtws.com/index.php/Wx/Prodetail/index/id/20/"
          ["signature"] => string(40) "a70ef78304bc4f5558439b65955119806e4fb3fe"
          ["rawString"] => string(205) "jsapi_ticket=HoagFKDcsGMVCIY2vOjf9raVdUJqZ1stwmkyXwhMyovuJhCTHjtpRnNxRJSVQ0UacAdrqz97vWdzjRU3Dp-YYw&noncestr=5cKMHQADQTbRkv2f*tamp=1527576256&url=http://www.xiangtws.com/index.php/Wx/Prodetail/index/id/20/"
        }
        *
        */
        $this->assign('signPackage',$signPackage);//微信数据
        //微信分享-end



        //申请成功或者失败
        if ($order['state'] != 0 && $member['is_me'] == 'true'){

            $this->display("success-sc02");

        }else{

            $this->display("success-sc");

        }//end if

    }//end fun foretaste()



    //活动核销

    public function receive(){

        $sn = $_GET['sn'];

        $op = $_POST['op'];

        $re_sn = explode('+',$sn);//参数处理

        $u_id = session("u_id");

        $order = M("foretaste_order")->where("id = {$re_sn[0]}")->find();//订单信息

        $foretaste = M("foretaste_goods")->where("id = {$order['g_id']}")->find();//商品信息

        $member = getMember($order['u_id']);

        $store = M("shop_store")->where("c_id = {$member['c_id']}")->find();//该社区店铺信息



        //登录用户是否为该订单店主
        $u_id_str = array();

        $u_id_str[0]=$store['u_id'];

        //获取店铺店员id
        if (!empty($store)){
            $clerk = M("shop_saler")->where("storeid = {$store['id']}")->field('u_id')->select();

            if (empty($clerk)){

                foreach ($clerk as $k => $v){

                    $u_id_str[$k+1]=$v['u_id'];

                }

            }//end if
        }//end if

//        $u_id_str[] = 1391;
        //是否有核销权限
        if(in_array($u_id,$u_id_str)){

            if ($op == 'receive'){

                $receive = M("foretaste_order")->where("id = {$order['id']}")->save(['state'=>4]);//订单信息

                if ($receive){

                    $this->ajaxReturn(array('val'=>'核销成功'),"json");

                }else{

                    $this->ajaxReturn(array('val'=>'核销失败'),"json");

                }

            }//end if

            //总成功订单
            $foretaste['sumorder'] = M("foretaste_order")->where("state in (1,2,3,4,5)")->getField('count(id)');//订单信息

            $this->assign('order',$order);

            $this->assign('member',$member);

            $this->assign($foretaste);

            $this->display("cancel");

        }else{
            $this->error("无操作权限",U('Index/index'));//无权限跳转地址
        }//end if

    } //end fun receive()

//    //申请列表
//
//    public function applylist(){
//
//        $gid = $_GET['gid'];//商品id
//
//        $goods = M("foretaste_goods")->where("id = {$gid} AND state = 1 ")->find();//获取商品信息
//
//        $order = M("foretaste_order")->where("g_id = {$gid} AND state != 6 ")->order("id,population,state desc")->select();//获取订单信息
//
//        $success_num = M("foretaste_order")->where("g_id = {$gid} AND state in(1,2,3,4,5)")->getField("count(id)");//获取成功订单
//
//        $goods['success_num'] = $success_num;
//
//
//
//        //获取订单用户昵称
//
//        foreach ($order as $k => $v){
//
//            $order[$k]['nickname'] = M('member')->where("id = {$v['u_id']}")->getField("nickname");
//
//            $order[$k]['avatar'] = M('member')->where("id = {$v['u_id']}")->getField("avatar");
//
//            $order[$k]['pre'] = ($v['population']/8)*100;//获取百分比值
//
//            $order[$k]['pre'] = $order[$k]['pre'] > 100? 100 :$order[$k]['pre'] ;//获取百分比值
//
//            $starttime = date("YmdHis",$v['addtime']);//获取开始时间
//
//            $endtime=strtotime($starttime.'+1 hour');//获取一个小时后的时间戳
//
//            $order[$k]['totime'] = $endtime-time()>0?$endtime-time():0;//获取剩余时间
//
//            $this->detector($v['id']);
//
//        }

//        dump($order);

//        $this->assign("order",$order);
//
//        $this->assign("goods",$goods);
//
//        $this->display("list-sc");
//
//    }//end fun applylist()

    //扶农大使-展示页
    public function helppoor(){
        $this->display("helppoor");
    }//end fun helppoor()

    //扶农大使-排名
    public function ranking(){
        $helppoor = M("helppoor")->where("state = 1")->getField('id');//获取排行活动id
        if (isset($helppoor)){
            $u_id = session('u_id');
            $cm = M('member')->where("id = {$u_id}")->getField('c_id');//获取当前用户的小区
            $type = $_POST['type'] ? $_POST['type'] : 'all';//状态

            if ($type == 'all'){
                $where = '';//总排名
            }//end if

            if($type == 'com'){
                $where = "c_id = {$cm} AND ";//小区排名
            }//end if

            $ranking = M("foretaste_ranking")->where($where."h_id = {$helppoor}")->order('eva_num desc')->select();//获取排行用户信息

            foreach($ranking as $k => $v){
                $ranking[$k]['member'] = getMember($v['u_id'],'nickname,avatar');//获取用户头像
                $ranking[$k]['ranking_id'] = $k+1;//获取名次
                $ranking[$k]['community'] = M("shop_community")->where("id = {$v['c_id']}")->getField('title');//获取小区名
            }//end foreach

            $this->assign('ranking',$ranking);

            $this->assign('u_id',$u_id);
            $this->assign('type',$type);
            $this->display("ranking");
        }else{
            $this->error('活动还未开始',U("Index/index"));
        }//end if
    }//end fun ranking()

}//end class